import { Player } from "@minecraft/server";
import { get_player_by_name } from "../utils/entity_filter/player_filter";
import { PLAYER_PROPERTY_KEY, PlayerProperty } from "../player_data/player_property";
import { DynamicJson } from "../dynamic_data/dynamic_json";

export class PlayerGroup {
    players: Set<Player>;
    id: string;

    constructor(id: string) {
        this.players = new Set<Player>();
        this.id = id;
    }

    addPlayer(player: Player) {
        new DynamicJson<PlayerProperty>(player, PLAYER_PROPERTY_KEY).update((val) => {
            let result = val;
            result.ids.add(this.id);
            return result;
        });

        player.addTag(this.id);

        this.players.add(player);
    }
    delPlayer(player: Player) {
        // let group_id = new DynamicData<string>(player, MOD_ID.of("group_id"));
        // group_id.free();

        new DynamicJson<PlayerProperty>(player, PLAYER_PROPERTY_KEY).update((val) => {
            let result = val;
            result.ids.delete(this.id);
            return result;
        });

        player.removeTag(this.id);

        this.players.delete(player);
    }
    contains(player: Player): boolean {
        return this.players.has(player);
    }
    getPlayers() {
        return Array.from(this.players);
    }
    free() {
        this.players.forEach((e) => {
            this.delPlayer(e);
        });
    }
}

export function getPlayerGroupId(playerName: string) {
    const player = get_player_by_name(playerName);
    if (player != undefined) {
        return new DynamicJson<PlayerProperty>(player, PLAYER_PROPERTY_KEY).get()?.ids;
    }
}
